let cachedBaseUrl;

const DEFAULT_BASE_URL = 'http://localhost:9090';
const ENV_BASE_URLS = {
	development: DEFAULT_BASE_URL,
	production: 'https://tally.meibug.cn:9090',
	test: DEFAULT_BASE_URL
};

function resolveInitialBaseUrl() {
	const saved = typeof uni !== 'undefined' ? uni.getStorageSync('BASE_URL') : '';
	if (saved) {
		return normalizeUrl(saved);
	}
	const env = typeof process !== 'undefined' ? process.env.NODE_ENV : 'development';
	const fallback = ENV_BASE_URLS[env] || DEFAULT_BASE_URL;
	return normalizeUrl(fallback);
}

function normalizeUrl(url) {
	if (typeof url !== 'string') {
		return DEFAULT_BASE_URL;
	}
	const trimmed = url.trim();
	return trimmed.endsWith('/') ? trimmed.slice(0, -1) : trimmed;
}

export function getBaseUrl() {
	if (!cachedBaseUrl) {
		cachedBaseUrl = resolveInitialBaseUrl();
	}
	return cachedBaseUrl;
}

export function setBaseUrl(url) {
	const normalized = normalizeUrl(url);
	cachedBaseUrl = normalized;
	if (typeof uni !== 'undefined') {
		uni.setStorageSync('BASE_URL', normalized);
	}
}

export function resetBaseUrl() {
	cachedBaseUrl = resolveInitialBaseUrl();
	if (typeof uni !== 'undefined') {
		uni.removeStorageSync('BASE_URL');
	}
	return cachedBaseUrl;
}

